import React, { Component } from 'react';
import { connect } from 'react-redux'
import { Modal, Form, Input,Select ,DatePicker ,Table,Button,TreeSelect,  Popconfirm,Row,Col,
  InputNumber} from 'antd';

import moment from 'moment';
// 推荐在入口文件全局设置 locale
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const Option=Select.Option;
const FormItem = Form.Item;
const TreeNode = TreeSelect.TreeNode;

const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
const formItemLayout1 = {
      labelCol: { span: 2 },
      wrapperCol: { span: 21 },
    };
var _this,attrValuesForm={},existsSerial=false;

class AddShelfDownModal extends Component {

  constructor(props) {
    super(props);
  }

  okHandler = () => {
     const { onOk } = this.props;
     this.props.form.validateFields((err, values) => {
      if (!err) {
        var list = [];
        _this.props.groupList.map((c)=>{
          c.attrList.map((d)=>{
            if(d.type == 5){
              var time = values[d.id_]?values[d.id_].toLocaleString():undefined;
              list.push({attrId: d.id_,value: time})
            }else{
              list.push({attrId: d.id_,value: values[d.id_]})
            }
          })
        })

        onOk({list: list, assetId: _this.props.assetId,values},_this.props.form.resetFields);
      }
     });
  };

  onCancel = ()=>{
    this.props.form.resetFields()
    this.props.onCancel()
  }

  handleRoomChange = (value) => {
    const { handleRoomChange } = this.props;
    if(value){
      handleRoomChange(value);
    }
  };

  handleBrandChange= (value) => {
    this.props.form.setFieldsValue({modelId: undefined});//设置modelId控件的值为空
    this.props.handleBrandChange({brandId:value,typeId:_this.props.form.getFieldValue("typeId")});
  };

  handleTypeChange= (value) => {
    this.props.form.setFieldsValue({modelId: undefined});//设置modelId控件的值为空
    this.props.handleBrandChange({typeId:value,brandId:_this.props.form.getFieldValue("brandId")});
  };

  getSelectOption = (str) => {
    var list = str.split(",");
    return list.map((d,index)=>(<Option key={index} value={d}>{d}</Option>))
  }

  getallForm = (list)=>list.map((d,index)=>(
    <div key={index}>
      <div style={{fontSize: 14,color: "#333", marginBottom: 10,}}>{d.name}</div>
      <div style={{marginBottom: 15,borderBottom: '1px solid #e9e9e9'}}></div>
      <Row>
        {_this.getFormItemList(d.attrList)}
      </Row>
    </div>
  ))

  getFormItemList = (list) => list.map((d,index)=>(
    <Col key={index} span={6}>
      {_this.getSwitchItem(d)}
    </Col>
  ))

  getSwitchItem = (item) => {
    switch(item.type){
      case 1:
        return (
            <FormItem
              {...formItemLayout}
              hasFeedback
              label={item.lable}
            >
              {
                _this.props.form.getFieldDecorator(item.id_, {
                  initialValue: attrValuesForm[item.id_],
                  rules: item.isNotNull?[
                    {required: true, message: '请输入'+item.lable},
                    {max: item.size, message: '长度不能超过'+item.size}
                  ]:[{max: item.size, message: '长度不能超过'+item.size},]
                })(<Input />)
              }
            </FormItem>
        )
      case 2:
        return (
            <FormItem
              {...formItemLayout}
              hasFeedback
              label={item.lable}
            >
              {
                _this.props.form.getFieldDecorator(item.id_, {
                  initialValue: attrValuesForm[item.id_]?attrValuesForm[item.id_]+"":undefined,
                  rules: item.isNotNull?[
                    {required: true, message: '请输入'+item.lable}
                  ]:[],
                })(<InputNumber min={1} max={item.size} style={{width: "100%"}}/>)
              }
            </FormItem>
        )
      case 3:
        return (
            <FormItem
              {...formItemLayout}
              hasFeedback
              label={item.lable}
            >
              {
                _this.props.form.getFieldDecorator(item.id_, {
                  initialValue: attrValuesForm[item.id_],
                  rules: item.isNotNull?[
                    {required: true, message: '请输入'+item.lable},
                    {max: item.size, message: '长度不能超过'+item.size}
                  ]:[{max: item.size, message: '长度不能超过'+item.size}],
                })(<Input.TextArea />)
              }
            </FormItem>
        )
      case 4:
        return (
            <FormItem
              {...formItemLayout}
              hasFeedback
              label={item.lable}
            >
              {
                _this.props.form.getFieldDecorator(item.id_, {
                  initialValue: attrValuesForm[item.id_],
                  rules: item.isNotNull?[
                    {required: true, message: '请输入'+item.lable},
                  ]:[],
                })(
                  <Select>
                    {_this.getSelectOption(item.options)}
                  </Select>
                )
              }
            </FormItem>
        )
      case 5:
        return (
            <FormItem
              {...formItemLayout}
              hasFeedback
              label={item.lable}
            >
              {
                _this.props.form.getFieldDecorator(item.id_, {
                  initialValue: attrValuesForm[item.id_]?moment(new Date(attrValuesForm[item.id_]), 'YYYY-MM-DD'):undefined,
                  rules: item.isNotNull?[
                    {required: true, message: '请输入'+item.lable},
                  ]:[],
                })(<DatePicker format="YYYY-MM-DD" showToday/>)
              }
            </FormItem>
        )
      default:
        return null;
    }
  }

  checkPrice = (rule, size,value, callback) => {
   
    console.log(size);
  }

  render() {
    const { children, dispatch,assetData,assetType,assetBrandList,assetModelList,roomList,rackList,manageDeptTree,useDeptTree,userList} = this.props;
    const { getFieldDecorator} = this.props.form;
    attrValuesForm =this.props.attrValuesForm;
    existsSerial=this.props.existsSerialNo;
    _this = this;

    const handleConfirmPassword = (rule, value, callback) => {
      console.log(value);
      var re = /^[1-9]+[0-9]*]*$/;
      if (!re.test(input.rate.value)){
          callback('两次输入不一致！')
      }
         callback()

   }

   
  const handleDeptChange = (value) => {
    this.props.form.setFieldsValue({endUser: undefined});//设置modelId控件的值为空
    dispatch({
      type: 'maintain/qryUserByDept',
      payload: {deptId:value },
    });       
  }
    const loop = data => data.map((item) => {
      if (item.assetType && item.assetType.length) {
        return <TreeNode key={item.id_+''} title={item.name} value={item.id_+''}>{loop(item.assetType)}</TreeNode>;
      }
      return <TreeNode key={item.id_+''} title={item.name} value={item.id_+''} />;
    });

    const treeData = (i) => {
      return i.map( d => {
        d.label = d.name;
        d.key = d.id_+'';
        d.value = d.id_+'';
        d.children = d.depts && d.depts.length > 0 ? treeData(d.depts) : [];
        return d;
      })
    }

    const typeTreeData = (i) => {
      return i.map( d => {
        d.label = d.name;
        d.key = d.id_+'';
        d.value = d.id_+'';
        d.children = d.assetType && d.assetType.length > 0 ? typeTreeData(d.assetType) : [];
        return d;
      })
   }

    const getBrand = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const getModel = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const getRoom = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const getRack = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.assetName}</Option>
    })
    const getUser = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })

    return (
      <span>
        <Modal
            maskClosable= {this.props.maskClosable}
            confirmLoading= {this.props.confirmLoading}
            title={this.props.title}
            top={50}
            width={1100}
            visible={this.props.visible}
            onOk={this.okHandler}
            onCancel={this.onCancel}
            key={this.props.newKey}
        >
         <div style={{width:'auto',position:'relative',backgroundColor:'#fff'}}>
            <div style={{minHeight:'100%'}}>
            <div style={{backgroundColor:'#fff',paddingLeft:'20px',paddingRight:'20px'}}>
                <Form >

                <div>
                  <div style={{fontSize: 14,color: "#333", marginBottom: 10,}}>资产属性</div>
                  <div style={{marginBottom: 15,borderBottom: '1px solid #e9e9e9'}}></div>
                  <Row>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="资产名称"
                      >
                        {
                          getFieldDecorator("assetName", {
                            initialValue: assetData.assetName,
                            rules: [{
                                    required: true, whitespace: true, message: '请输入资产名称',
                                  },{ max: 30, message: '资产名称 30 字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="资产编号"
                      >
                        {
                          getFieldDecorator("assetNo", {
                            initialValue: assetData.assetNo,
                            rules: [{
                                    required: true, whitespace: true, message: '请输入资产编号',
                                  },{ max: 20, message: '资产编号 20 字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="序列号"
                      >
                        {
                          getFieldDecorator("serialNo", {
                            initialValue: assetData.serialNo,
                            rules: [{validator: this.checkSerialNo,
                                    required: true, whitespace: true, message: '请输入资产序列号',
                                  },{ max: 20, message: '序列号 20 字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="RFID号"
                      >
                        {
                          getFieldDecorator("rfidNo", {
                            initialValue: assetData.rfidNo,
                             rules: [{
                                    required: true, whitespace: true, message: '请输入资产RFID号',
                                  },{ max: 20, message: 'RFID号 20 字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="资产类型"
                      >
                        {
                          getFieldDecorator("typeId", {
                            initialValue: assetData.typeId_,
                             rules: [{
                                    required: true, whitespace: true, message: '请选择资产类型',
                                  }]
                          })(
                            <TreeSelect
                              showSearch
                              treeNodeFilterProp="title"
                              notFoundContent="无匹配结果"
                              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                              placeholder="请选择资产分类"
                              allowClear
                              onChange={this.handleTypeChange}
                              treeDefaultExpandAll
                              treeData={typeTreeData(assetType)}                              
                            >
                            </TreeSelect>
                          )
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="品牌"
                      >
                        {
                          getFieldDecorator("brandId", {
                            initialValue: assetData.brandId_,
                             rules: [{
                                    required: true, whitespace: true, message: '请选择品牌',
                                  }]
                          })(
                            <Select
                              showSearch
                              allowClear
                              onChange={this.handleBrandChange}
                              placeholder="请选择品牌">

                              {getBrand(assetBrandList)}
                            </Select>
                          )
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="型号"
                      >
                        {
                          getFieldDecorator("modelId", {
                            initialValue: assetData.modelId_,
                             rules: [{
                                    required: true, whitespace: true, message: '请选择型号',
                                  }]
                          })(
                            <Select
                              showSearch
                              allowClear
                              placeholder="请选择型号">
                              {getModel(assetModelList)}
                            </Select>
                          )
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="价格"
                      >
                        {
                          getFieldDecorator("price", {
                            initialValue: assetData.price,
                             rules: [{ required: true, message: '请填写价格' }]
                          })(<InputNumber max={99999999}/>)
                        }
                      </FormItem>
                    </Col>

                  </Row>
                  <Row>
                   {/* <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="2.4G标签"
                      >
                        {
                          getFieldDecorator("rfidNo1", {
                            initialValue: assetData.rfidNo1,
                             rules: [{ max: 20, message: '2.4G标签 20 字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col> */}                   
                     <FormItem
                        hasFeedback
                        {...formItemLayout1}
                        label="设备描述"
                      >
                        {
                          getFieldDecorator("remark", {
                            initialValue: assetData.remark,
                             rules: [{ max: 100, message: '设备描述在 100 字符以内' }]
                          })(<Input type="textarea" autosize={{ minRows:2, maxRows: 2 }} />)
                        }
                      </FormItem>
                   
                  </Row>
                </div>

                <div>
                  <div style={{fontSize: 14,color: "#333", marginBottom: 10,}}>资产扩展属性</div>
                  <div style={{marginBottom: 15,borderBottom: '1px solid #e9e9e9'}}></div>
                  <Row>
                   <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="IP地址"
                      >
                        {
                          getFieldDecorator("ip", {
                            initialValue: assetData.ip,
                            rules: [{
                                    max:30, message: 'IP 30 个字符以内',
                                  }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="所在位置"
                      >
                        {
                          getFieldDecorator("roomId", {
                            initialValue: assetData.roomId_,
                            rules: [{
                                    required: true, whitespace: true, message: '请选择所在位置',
                                  }]
                          })(
                            <Select
                              showSearch
                              allowClear
                              onChange={this.handleRoomChange}
                              placeholder="请选择所在位置">
                              {getRoom(roomList)}
                            </Select>
                          )
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="机柜"
                      >
                        {
                          getFieldDecorator("rackId", {
                            initialValue: assetData.rackId_,
                            rules: [{
                                    required: true, whitespace: true, message: '请选择所在机柜',
                                  }]
                          })(
                            <Select
                              showSearch
                              allowClear
                              placeholder="请选择所在机柜">
                              {getRack(rackList)}
                            </Select>
                            )
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="起始U"
                      >
                        {
                          getFieldDecorator("startU", {
                            initialValue: assetData.startU,
                            rules: [{ required: true, message: '请输入起始U',}]
                          })(<Input type="number" />)
                        }
                      </FormItem>
                    </Col>
                  </Row>
                </div>
                <div>
                  <div style={{fontSize: 14,color: "#333", marginBottom: 10,}}>资产使用属性</div>
                  <div style={{marginBottom: 15,borderBottom: '1px solid #e9e9e9'}}></div>
                  <Row>
                    <Col span={6}>
                    <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="管理部门"
                      >
                         {
                          getFieldDecorator('manageBranchId', {
                            initialValue: assetData.manageBranchId_?assetData.manageBranchId_:undefined,                          
                          })(
                            <TreeSelect
                              showSearch
                              treeNodeFilterProp="title"
                              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                              placeholder="请选择管理部门"
                              allowClear
                              treeData={treeData(manageDeptTree)}
                              treeDefaultExpandAll
                            >                            
                            </TreeSelect>
                          )
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="使用部门"
                      >                       
                         {
                          getFieldDecorator('useBranchId', {
                            initialValue: assetData.useBranchId_?assetData.useBranchId_:undefined,                          
                          })(
                            <TreeSelect
                              showSearch
                              treeNodeFilterProp="title"
                              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                              placeholder="请选择使用部门"
                              allowClear
                              treeData={treeData(useDeptTree)}
                              onChange={handleDeptChange}
                              treeDefaultExpandAll
                            >                            
                            </TreeSelect>
                          )
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="使用人"
                      >
                       {
                          getFieldDecorator('endUser', {
                            initialValue: assetData.endUser?assetData.endUser:undefined,                          
                          })(
                            <Select
                             showSearch
                             placeholder="使用人"
                             optionFilterProp="children"
                            >
                             {getUser(userList)}
                          </Select>
                          )
                        }
                        
                      </FormItem>
                    </Col>
                                 
                  </Row>
                </div>
                <div>
                  <div style={{fontSize: 14,color: "#333", marginBottom: 10,}}>资产维保属性</div>
                  <div style={{marginBottom: 15,borderBottom: '1px solid #e9e9e9'}}></div>
                  <Row>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="供货方"
                      >
                        {
                          getFieldDecorator("supplier", {
                            initialValue: assetData.supplier,
                            rules: [{
                                    max:30, message: '供货方 30 个字符以内',
                                  }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="联系人"
                      >
                        {
                          getFieldDecorator("contacts", {
                            initialValue: assetData.contacts,
                            rules: [{
                                     max:30, message: '联系人 30 个字符以内',
                                  }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="联系电话"
                      >
                        {
                          getFieldDecorator("contactsPhone", {
                            initialValue: assetData.contactsPhone,
                            rules: [{
                                     max:20, message: '联系电话 20 个字符以内',
                                  }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="售后电话"
                      >
                        {
                          getFieldDecorator("hotline", {
                            initialValue: assetData.hotline,
                             rules: [{ max: 20, message: '售后电话 20 个字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="合同号"
                      >
                        {
                          getFieldDecorator("contractNo", {
                            initialValue: assetData.contractNo,
                             rules: [{ max: 20, message: '合同号 20 个字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>

                    <Col span={6}>
                     <FormItem
                        {...formItemLayout}
                        hasFeedback
                        label="发票号"
                      >
                        {
                          getFieldDecorator("invoiceNo", {
                            initialValue: assetData.invoiceNo,
                             rules: [{ max: 20, message: '合同号 20 个字符以内' }]
                          })(<Input />)
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem
                          {...formItemLayout}
                          label="购置时间"
                          >
                          {getFieldDecorator('buyTime', {
                            initialValue:assetData.buyTime?moment(assetData.buyTime):"",
                          })(<DatePicker />)}
                      </FormItem>
                    </Col>
                      <Col span={6}>
                        <FormItem
                          {...formItemLayout}
                          label="保修到期时间"
                          >
                          {getFieldDecorator('expirationTime', {
                            initialValue:assetData.expirationTime?moment(assetData.expirationTime):"",
                          })(<DatePicker />)}
                      </FormItem>
                    </Col>

                  </Row>
                </div>


                  {_this.getallForm(this.props.groupList)}

                </Form>
            </div>

            </div>
        </div>
        </Modal>

      </span>
    );
  }

}

export default Form.create()(AddShelfDownModal)
